﻿using System.Data;
using System.Linq;
using System.Web.Mvc;
using Pyramid.Models;

namespace Pyramid.Controllers
{
	/// <summary>
	/// 工资组成部分管理
	/// </summary>
	public class SalaryPartController : BaseController
	{
		public ActionResult List()
		{
			return View(Db.SalaryParts);
		}

		public ActionResult Create()
		{
			var model = new SalaryPart {CalculateType = (int) CalculateTypes.Add, DisplayFormat = "C"};
			return View("Edit", model);
		}

		public ActionResult Edit(int id)
		{
			var model = Db.SalaryParts.First(x => x.Id == id);
			return View(model);
		}

		[HttpPost]
		public ActionResult Edit(SalaryPart model)
		{
			//名称不能重复
			if (Db.SalaryParts.Any(x => x.Id != model.Id && x.Code == model.Code))
			{
				return JError("编码已占用，请重新修改！");
			}

			if (model.Id == 0)
			{
				//只能添加添加自定义类型的工资组成部分
				model.SalaryPartType = (int) SalaryPartTypes.Custom;
				//用户自定义的类型格式只能是 C
				model.DisplayFormat = "C";
				Db.SalaryParts.Add(model);
			}
			else
			{
				if (model.SalaryPartType == (int) SalaryPartTypes.System)
				{
					return JError("系统内置部分，不能修改！");
				}
				//修改
				Db.Entry(model).State = EntityState.Modified;
			}
			Db.SaveChanges();
			return JSuccess("操作成功！", "tab_sal_salarypart");
		}

		public ActionResult Delete(int id)
		{
			var model = Db.SalaryParts.First(x => x.Id == id);
			if (model.SalaryPartTypeEnum == SalaryPartTypes.System)
			{
				return JError("系统内置部分，不能删除！");
			}

			Db.Entry(model).State = EntityState.Deleted;
			Db.SaveChanges();
			return JSuccess("删除成功！", "tab_sal_salarypart");
		}
	}
}